package com.dhq.myapp.util


import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import java.security.MessageDigest
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * DESC
 * Created by admin on 2017/3/28.
 */

object DataUtils {

    /**
     * 将Map转化为Json
     */
    fun <T> mapToJson(map: Map<String, T>): String {
        return gsonMapToJson(map)
    }

    fun jsonToMap(json: String): Map<*, *> {
        val gson = Gson()
        return gson.fromJson(json, Map::class.java)
    }

    /**
     * 利用Gson将Map转化为Json
     */
    private fun gsonMapToJson(map: Map<*, *>): String {
        val gson = Gson()
        return gson.toJson(map)
    }

    /**
     * 利用Gson将Object转化为Json
     */
    fun gsonObjectToJson(obj: Any): String {
        val gson = Gson()
        return gson.toJson(obj)
    }

    /**
     * 利用Gson将Object转化为Object
     */
    fun <T> gsonObjectToObject(obj: Any, clazz: Class<T>): T {
        val gson = Gson()
        val jsonStr = gson.toJson(obj)
        return gson.fromJson(jsonStr, clazz)
    }

    /**
     * 将JsonElement转换为List
     */
    fun <T> jsonToList(json: JsonElement, clazz: Class<T>): List<T> {
        val type = ParameterizedTypeImpl(clazz)
        return Gson().fromJson(json, type)
    }

    /**
     * 将Json字符串转换为List
     */
    fun <T> jsonToList(json: String, clazz: Class<T>): List<T> {
        val type = ParameterizedTypeImpl(clazz)
        return Gson().fromJson(json, type)
    }

    /**
     * 将Json字符串转换为ArrayList
     */
    fun <T> jsonToArrayList(json: String, clazz: Class<T>): ArrayList<T> {
        val type = ParameterizedTypeImpl(clazz)
        return Gson().fromJson(json, type)
    }

    /**
     * 将Json字符串转换为对象
     */
    fun <T> jsonToObject(json: String, clazz: Class<T>): T {
        return Gson().fromJson(json, clazz)
    }

    /**
     * 对数据MD5加密
     */
    fun MD5(inStr: String): String {
        val md5 = try {
            MessageDigest.getInstance("MD5")
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }

        val byteArray = inStr.toByteArray()
        val md5Bytes = md5.digest(byteArray)
        val hexValue = StringBuilder()

        for (i in md5Bytes.indices) {
            val value = md5Bytes[i].toInt() and 0xFF
            if (value < 16) {
                hexValue.append("0")
            }
            hexValue.append(Integer.toHexString(value))
        }
        return hexValue.toString()
    }

    private class ParameterizedTypeImpl(private val clazz: Class<*>) : ParameterizedType {
        override fun getActualTypeArguments(): Array<Type> {
            return arrayOf(clazz)
        }

        override fun getRawType(): Type {
            return List::class.java
        }

        override fun getOwnerType(): Type? {
            return null
        }
    }
}
